package cn.edu.lzzy.services.Impl;

import cn.edu.lzzy.dao.CourseRepository;
import cn.edu.lzzy.entities.Course;
import cn.edu.lzzy.entities.Messages;
import cn.edu.lzzy.services.CourseService;
import cn.edu.lzzy.utils.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Service
public class CourseServiceImpl implements CourseService {
    private final CourseRepository courseRepository;
    @Autowired
    public CourseServiceImpl(CourseRepository courseRepository){
        this.courseRepository = courseRepository;
    }
    @Override
    public List<Course> getCourse() {
        return courseRepository.findAllByOrderByUpdateTimeDesc();
    }
    @Override
    public List<Course> getCourseByPage(int page, int size) {
        return courseRepository.findAllByOrderByUpdateTimeDesc( PageRequest.of(page,size));
    }
    @Override
    public Integer count() {
        return courseRepository.countAllBy();
    }
    @Override
    public List<Course> getTeachersCourse(UUID teacherId) {
        return courseRepository.findCourseByTeacherIdEqualOrderByCreateTime(teacherId);
    }
    @Override
    public List<Course> getStudentsCourse(UUID student) {
        return courseRepository.findCourseByStudentsContainsAAndOpenOrderByUpdateTime(student,true);
    }
    @Override
    public Course add(Course course) {
        return courseRepository.saveAndFlush(course);
    }
    @Override
    public Course update(Course course, String token) {
        UUID teacherId=course.getTeacher().getId();
        if(AuthUtils.invalid(teacherId,token)){
            return null;
        }
        course.setUpdateTime(new Date());
        return courseRepository.save(course);
    }
    @Override
    public Course getCourseById(UUID courseId) {
        return courseRepository.findById(courseId).orElse(null);
    }
    @Override
    public Messages remove(UUID courseId, String token) {
        Course course=courseRepository.findById(courseId).orElse(null);
        if(course==null){
            return Messages.WRONG_ID;
        }
        UUID teacherId = course.getTeacher().getId();
        if (AuthUtils.invalid(teacherId,token)){
            return Messages.NO_PERMISSION;
        }
        if (course.getChapters().size()>0 || course.getApplicants().size()>0 || course.getStudents().size()>0){
            return Messages.RELATED_DATA;
        }
        courseRepository.delete(course);
        return null;
    }
}